package cn.hyy.hrm.controller;


import cn.hyy.basic.util.AjaxResult;
import cn.hyy.hrm.util.RedisUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;

@RestController
public class RedisController {

    /**
     * 设置字符值
     * @param key
     * @param value
     * @return
     */
    @GetMapping("/redis/setStr")
    public AjaxResult setStr(String key, String value){
        try {
            RedisUtils.INSTANCE.set(key,value);
            return AjaxResult.me().setSuccess(true).setMessage("缓存成功!");
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("缓存失败!");
        }
    }


    /**
     * 获取字符值
     * @param key
     * @return
     */
    @GetMapping("/redis/getStr")
    public AjaxResult getStr(String key){
        try {
            String value = RedisUtils.INSTANCE.get(key);
            return AjaxResult.me().setSuccess(true).setMessage("查询成功!").setResultObj(value);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("查询失败!");
        }
    }

    /**
     * 设置字符值（有过期时间）
     * @param key
     * @param value
     * @return
     */
    @GetMapping("/redis/setStrEX")
    public AjaxResult setStrEX(String key,String value,Integer seconds){
        Jedis source = null;
        try {
            source = RedisUtils.INSTANCE.getSource();
            source.setex(key,seconds,value);
            return AjaxResult.me().setSuccess(true).setMessage("缓存成功!");
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("缓存失败!");
        } finally {
            source.close();
        }
    }
    /**
     * 判断key值是否存在
     * @param key
     * @return
     */
    @GetMapping("/redis/exists")
    public AjaxResult exists(@RequestParam("key") String key){
        Jedis source = null;
        try {
            source = RedisUtils.INSTANCE.getSource();
            Boolean exists = source.exists(key);
            return AjaxResult.me().setSuccess(true).setResultObj(exists);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("系统异常");
        } finally {
            source.close();
        }
    }

}
